import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/animation.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/flutter_svg.dart' as svg;
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:hixing_app/assets/r_img.dart';
import 'package:hixing_app/views/test_view/canvas_utils.dart';
import 'package:hixing_app/views/test_view/test_matrix4/rect_element_model.dart';

class TestMatrix4 extends StatefulWidget {
  @override
  _TestMatrix4State createState() => _TestMatrix4State();
}

class _TestMatrix4State extends State<TestMatrix4> {
  // 图标列表切换
  List<svg.PictureInfo> _svgList = [];
  List<svg.PictureInfo> _svgUnlockList = [];

  // 点击事件矩形域列表
  List<RectInfoModel> rectElements = [];

  // 绘制的企鹅 svg
  PictureInfo? imgSvgPicture;

  // 当前操作事件的类型
  CanvasEventType? eventType;

  // 是否显示操作框以及操作按钮
  bool showAction = false;

  // svg 数据
  double svgIconOffset = 5;
  Size svgIconSize = const ui.Size(30, 30);

  // 起始坐标偏移量
  double dx = 100;
  double dy = 100;

  // ui.Offset? _startOffset;

  // 触摸点dx跟dy坐标跟起始dx dy修正
  double odx = 0;
  double ody = 0;

  //svg  偏移量 ,用来计算触摸缩放的时候 点一下会放大的bug
  double correctSvgDx = 0;
  double correctSvgDy = 0;

  // 缩放的x，缩放的y
  double scaleX = 1;
  double scaleY = 1;

  // 是否锁定
  bool isLock = true;

  // 缩放的rect，
  ui.Rect? scaleRenderRect;

  // 图片的原始尺寸
  ui.Size imgSize = ui.Size(100, 100);

  // 缩放操作后渲染的图片尺寸
  // ui.Size renderImgSize = ui.Size(100, 100);

  // isRotate 翻转

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setPreferredOrientations(// 使设备横屏显示
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    loadImg();
    loadSvg();
  }

  Future<void> loadImg() async {
    var pgSvg = await rootBundle.loadString(ImgR.imgBgPguinSVG);
    final svg.PictureInfo pictureInfo1 = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          pgSvg,
        ),
        null);
    setState(() {
      imgSvgPicture = pictureInfo1;
    });
  }

  Future<ui.Image>? loadImageFromAssets(String path) async {
    ByteData data = await rootBundle.load(path);
    return decodeImageFromList(data.buffer.asUint8List());
  }

  Future<void> loadSvg() async {
    var svgDelete = await rootBundle.loadString(ImgR.imgBgDeleteIcon);
    final svg.PictureInfo pictureInfoDelete = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgDelete,
        ),
        null);

    var svgLock = await rootBundle.loadString(ImgR.imgBgLockIcon);
    final svg.PictureInfo pictureInfoLock = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgLock,
        ),
        null);

    var svgRotate = await rootBundle.loadString(ImgR.imgBgRotateIcon);
    final svg.PictureInfo pictureInfoRotate = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgRotate,
        ),
        null);
    var svgScale = await rootBundle.loadString(ImgR.imgBgScaleIcon);
    final svg.PictureInfo pictureInfoScale = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgScale,
        ),
        null);

    var svgUnlock = await rootBundle.loadString(ImgR.imgBgUnlock);
    final svg.PictureInfo pictureInfoUnlock = await svg.vg.loadPicture(
        svg.SvgStringLoader(
          svgUnlock,
        ),
        null);
    _svgList = [];
    _svgUnlockList = [];

    setState(() {
      _svgList.addAll([
        pictureInfoDelete,
        pictureInfoLock,
        pictureInfoRotate,
        pictureInfoScale,
      ]);
      _svgUnlockList.addAll([
        pictureInfoDelete,
        pictureInfoUnlock,
        pictureInfoRotate,
        pictureInfoScale,
      ]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Listener(
        onPointerUp: (details) {},
        onPointerSignal: (event) {
          print("双指捕捉 ${event.pointer}");
          if (event is PointerScrollEvent && event.scrollDelta != null) {
            print("捕获缩放手势");
            // 捕获缩放手势
            // final newScale = _scale * (1.0 - event.scrollDelta!.dy / 1000.0);
            // setState(() {
            //   _scale = newScale.clamp(0.5, 2.0); // 限制缩放范围为0.5到2.0
            // });
          }
        },
        onPointerMove: (details) {
          // print("触摸点数 ${details.pointer}");
          // 捕捉双指操作
          if (details.buttons == 2) {
            print("捕捉双指移动");
            // 计算双指中心点位置
            // final newScale = _scale * event.distance / event.initialDistance;
            // final newOffset = _offset + (event.localDelta - event.localDelta / _scale);
            //
            // setState(() {
            //   _scale = newScale.clamp(0.5, 2.0); // 限制缩放范围为0.5到2.0
            //   _offset = newOffset;
            // });
          }

          // 获取点击的位置
          final RenderBox renderBox = context.findRenderObject() as RenderBox;
          // 需要初始值加上默认的偏移量
          final globalPosition = renderBox.localToGlobal(details.localPosition);

          if (showAction && eventType == CanvasEventType.image) {
            // 平移元素操作
            setState(() {
              dx = globalPosition.dx - odx;
              dy = globalPosition.dy - ody;
            });
          } else if (showAction && eventType == CanvasEventType.scale) {
            //使用 imageSize 缩放
            /* double useNum = localPosition.dx - dx > localPosition.dy - dy
                ? localPosition.dx - dx
                : localPosition.dy - dy;
            ui.Rect _rect = ui.Rect.fromLTRB(0, 0, useNum, useNum);
            print(_rect.width);
            setState(() {
              scaleRect = _rect;
            });*/

            // 使用矩阵 缩放
            // 用当前手指触摸到0的坐标计算缩放的盒子尺寸，然后需要计算出触摸点的svgicon尺寸的偏移量，然后减去svgicon的偏移量，就不会点一下 放大一下了
            double _currentDx = globalPosition.dx - dx - correctSvgDx;
            double _currentDy = globalPosition.dy - dy - correctSvgDy;

            ui.Rect _rect;
            // if (isLock) {
            //   // 如果是锁定的，计算好尺寸比例，然后再塞进去盒子里
            //   double scaleW = _currentDx / imgSize.width;
            //   double scaleH = _currentDy / imgSize.height;
            //   // 如果锁定，使用均分的比例缩放，如果不锁定，就是不锁定的比例，获取缩放后的宽度，就是用计算好的缩放比例，用初始的宽高比计算最终渲染后的宽高
            //   double _lockScale = (scaleW + scaleH) / 2;
            //   // 把等比缩放的尺寸计算出来，画入rect里面
            //   _rect = ui.Rect.fromLTRB(
            //     0,
            //     0,
            //     imgSize.width * _lockScale,
            //     imgSize.height * _lockScale,
            //   );
            // } else {
            //
            // }
            // 如果不锁定，就根据手指触摸的坐标缩放就行了
            _rect = ui.Rect.fromLTRB(0, 0, _currentDx < 20 ? 20 : _currentDx,
                _currentDy < 20 ? 20 : _currentDy);
            scaleRenderRect = _rect;
            double scaleW = scaleRenderRect!.width / imgSize.width;
            double scaleH = scaleRenderRect!.height / imgSize.height;
            // 如果锁定，使用均分的比例缩放，如果不锁定，就是不锁定的比例
            double _lockScale = (scaleW + scaleH) / 2;
            if (isLock) {
              // 如果锁定，等比缩放
              scaleX = _lockScale;
              scaleY = _lockScale;
            } else {
              //如果没锁定，根据触摸的坐标缩放
              scaleX = scaleW;
              scaleY = scaleH;
            }
            setState(() {});
          } else if (showAction && eventType == CanvasEventType.rotate) {}
        },
        onPointerDown: (details) {
          // 获取点击的位置
          final RenderBox renderBox = context.findRenderObject() as RenderBox;
          // 需要初始值加上默认的偏移量
          final globalPosition = renderBox.localToGlobal(details.localPosition);
          final offsetLocal = globalPosition - ui.Offset(dx, dy);
          // _startOffset = globalPosition;

          //svgIcon 点击偏移量修正
          // 计算缩放后的偏移量，如果还没开始缩放，就是原始尺寸的宽高
          double computedWidth = scaleRenderRect == null
              ? imgSize.width
              : imgSize.width * (scaleRenderRect!.width / imgSize.width);
          double computedHeight = scaleRenderRect == null
              ? imgSize.height
              : imgSize.height * (scaleRenderRect!.height / imgSize.height);

          // 计算svgicon的偏移量，修正缩放的点击坐标
          correctSvgDx = globalPosition.dx - (dx + computedWidth);
          correctSvgDy = globalPosition.dy - (dy + computedHeight);

          //平移偏移量修正,修正后
          odx = globalPosition.dx - dx;
          ody = globalPosition.dy - dy;
          bool isContains = false;
          // 检查点击的位置是否在元素范围内
          for (var element in rectElements) {
            if (element.rect.contains(offsetLocal)) {
              // 处理点击事件
              print('Element clicked: ${element.type}');
              eventType = element.type;
              if ((element.type == CanvasEventType.image) && !showAction) {
                setState(() {
                  showAction = true;
                });
                print("打印出来状态了${showAction}  ");
              } else if ((element.type == CanvasEventType.lock) && showAction) {
                print("锁定点击  ");
                setState(() {
                  isLock = !isLock;
                  print(
                      "计算等比缩放后的尺寸 width: ${imgSize.width * scaleX},height:${imgSize.height * scaleY}");
                  // 锁定的时候，把当前的尺寸重置为上次锁定的尺寸,重置缩放的scaleX跟scaleY，清空renderRect，不然操作框的size计算不准，因为那里又*了一边scaleX跟scaleY
                  if (scaleRenderRect != null) {
                    imgSize = ui.Size(
                        imgSize.width * scaleX, imgSize.height * scaleY);
                    scaleRenderRect = null;
                    scaleX = 1;
                    scaleY = 1;
                  }
                  // if (scaleRenderRect != null) {
                  //   imgSize = ui.Size(scaleRenderRect!.width * scaleX,
                  //       scaleRenderRect!.height * scaleY);
                  //   scaleRenderRect = null;
                  // }
                  // if (scaleRenderRect != null) {
                  // imgSize = ui.Size(
                  //     scaleRenderRect!.width, scaleRenderRect!.height);
                  // scaleRenderRect = null;
                  // }
                });
              }
              isContains = true;
              break;
            }
          }
          if (!isContains) {
            setState(() {
              showAction = false;
              eventType = null;
            });
          }
        },
        child: Stack(
          children: [
            CustomPaint(
              size: ui.Size.infinite,
              painter: MyCustomPainter(
                  svgList: isLock ? _svgList : _svgUnlockList,
                  isLock: isLock,
                  scaleX: scaleX,
                  scaleY: scaleY,
                  // imgData: imgData,
                  showAction: showAction,
                  imgSvgPicture: imgSvgPicture,
                  imgSize: imgSize,
                  scaleRect: scaleRenderRect,
                  dx: dx,
                  dy: dy,
                  rectElements: rectElements),
            ),
            Positioned(
                top: 30,
                left: 30,
                child: Container(
                  decoration: BoxDecoration(
                      color: Colors.black26,
                      borderRadius: BorderRadius.circular(40)),
                  child: IconButton(
                    onPressed: () {
                      Get.back();
                    },
                    icon: Icon(
                      Icons.arrow_back,
                      color: Colors.yellowAccent,
                      size: 30,
                    ),
                  ),
                ))
          ],
        ),
      ),
    );
  }
}

class MyCustomPainter extends CustomPainter {
  MyCustomPainter(
      {required this.svgList,
      required this.rectElements,
      // this.imgData,
      this.imgSvgPicture,
      this.isLock = true,
      required this.dx,
      required this.dy,
      required this.scaleX,
      required this.scaleY,
      this.scaleRect,
      this.imgSize = const ui.Size(100, 100),
      this.svgIconSize = const ui.Size(30, 30),
      this.svgIconOffset = 5.0,
      this.showAction = false});

  List<svg.PictureInfo> svgList;

  //double svg偏移量
  final double svgIconOffset;

  // size svgSize
  final ui.Size svgIconSize;

  // 是否显示操作框框
  bool showAction;

  // 点击矩形域添加
  List<RectInfoModel> rectElements;

  // ui.Image? imgData;
  svg.PictureInfo? imgSvgPicture;
  final ui.Size imgSize;

  // 锁定
  final bool isLock;

  // 初始化偏移量
  final double dx;
  final double dy;

  // 缩放尺寸
  final double scaleX;
  final double scaleY;

  final ui.Rect? scaleRect;

  @override
  void paint(Canvas canvas, ui.Size size) {
    // TODO: implement paint
    // TODO: implement paint
    Paint _paint = Paint();

    // canvas.translate(size.width / 2, size.height / 2);

    // 绘制坐标以及网格
    // _drawGrid(canvas, _paint, size);
    // _drawCoor(canvas, _paint, size);
    CanvasUtils.drawGrid(canvas, _paint, size);
    CanvasUtils.drawCoor(canvas, _paint, size);

    if (imgSvgPicture != null) {
      // 清除上一次矩形域列表
      rectElements.clear();
      final count = canvas.getSaveCount();
      canvas.save();
      // 平移到初始化偏移量
      canvas.translate(dx, dy);
      final scaleCount = canvas.getSaveCount();

      // if (true) {
      //   canvas.save();
      //   // 保存翻转前的状态
      //   ui.Offset centerOffset =
      //       ui.Offset(imgSize.width / 2, imgSize.height / 2);
      //   canvas.translate(centerOffset.dx, centerOffset.dy);
      //   const angle = pi / 4; // pi =半径，180度，180度/4 = 45度 旋转角度为45度
      //   final rotationMatrix = Matrix4.rotationZ(angle);
      //
      //   // 应用矩阵变换
      //   canvas.transform(rotationMatrix.storage);
      //   canvas.translate(-centerOffset.dx, -centerOffset.dy);
      // }

      if (scaleRect != null) {
        // 保存缩放前的状态
        canvas.save();
        // 创建一个缩放矩阵
        var matrix = Matrix4.identity();

        matrix.scale(scaleX, scaleY);
        canvas.transform(matrix.storage);
      }
      // 绘制企鹅 svg  尺寸是imgSize
      drawResizeSvg(
          canvas, imgSvgPicture!.picture, imgSize, imgSvgPicture!.size,
          color: null);
      canvas.restoreToCount(scaleCount);
      // 获取图片的尺寸，给事件矩形域列表添加一个rect
      final imgRect = Offset.zero & imgSize;
      // 计算最终渲染的rect，不锁定就设置为dx跟dy，等比例缩放就要计算等比缩放后的rect
      ui.Rect? _renderScaleRect;
      if (!isLock) {
        _renderScaleRect = ui.Rect.fromLTRB(
            0, 0, imgSize.width * scaleX, imgSize.height * scaleY);
      } else {
        // 如果不锁定，就根据手指触摸的坐标缩放就行了
        _renderScaleRect = ui.Rect.fromLTRB(
            0, 0, imgSize.width * scaleX, imgSize.height * scaleY);
      }

      rectElements.add(RectInfoModel(
          rect: _renderScaleRect ?? imgRect, type: CanvasEventType.image));

      // 绘制svg图片的边框
      canvas.drawRect(
          _renderScaleRect ?? imgRect,
          _paint
            ..style = ui.PaintingStyle.stroke
            ..color = showAction == true
                ? Colors.deepOrangeAccent
                : Colors.transparent);

      // 绘制四个角的操作按钮
      if (showAction) {
        List<RectInfoModel> rectList = drawSvgIcon(canvas, _paint,
            iconOffset: svgIconOffset,
            iconSize: svgIconSize,
            boxSize: _renderScaleRect == null ? imgSize : _renderScaleRect.size,
            svgList: svgList);
        rectElements.addAll(rectList);
      }
      canvas.restoreToCount(count);
    }

    // _drawSvgIcon(canvas, _paint);
    // canvas.drawRect(
    //     ui.Rect.fromCenter(center: ui.Offset.zero, width: 50, height: 50),
    //     _paint);
  }

  // 根据size 缩放图片
  // void resizeImg(Canvas canvas, ui.Size size, ui.Image img, Paint paint,
  //     {double x = 0, double y = 0}) {
  //   double cmpWidth = 0;
  //   double cmpHeight = 0;
  //
  //   if (img.width > img.height) {
  //     cmpHeight = (size.width / img.width) * img.height;
  //   } else if (img.width < img.height) {
  //     cmpWidth = (size.height / img.height) * img.width;
  //   }
  //   double renderWidth = cmpWidth == 0 ? size.width : cmpWidth;
  //   double renderHeight = cmpHeight == 0 ? size.height : cmpHeight;
  //   canvas.save();
  //   canvas.translate(dx, dy);
  //   final count = canvas.getSaveCount();
  //   // Draw image with scaled width
  //   if (scaleRect != null) {
  //     // 保存缩放前的状态
  //     canvas.save();
  //     // 创建一个缩放矩阵
  //     var matrix = Matrix4.identity();
  //     double scaleW = scaleRect!.width / imgSize.width;
  //     double scaleH = scaleRect!.height / imgSize.height;
  //     // 如果锁定，使用均分的比例缩放，如果不锁定，就是不锁定的比例
  //     double _lockScale = (scaleW + scaleH) / 2;
  //     matrix.scale(isLock ? _lockScale : scaleW, isLock ? _lockScale : scaleH);
  //     canvas.transform(matrix.storage);
  //     // canvas.drawRect(
  //     //     scaleRect!,
  //     //     paint
  //     //       ..style = ui.PaintingStyle.stroke
  //     //       ..color = Colors.deepOrangeAccent);
  //   }
  //
  //   if (true) {
  //     // 保存翻转前的状态
  //     canvas.save();
  //     canvas.translate(0, 0);
  //     double _rotateOffsetX = -imgSize.width / 2;
  //     double _rotateOffsetY = -imgSize.height / 2;
  //
  //     const angle = math.pi / 20; // pi =半径，180度，180度/4 = 45度 旋转角度为45度
  //
  //     // final rotationMatrix = Matrix4.rotationZ(angle);
  //
  //     // 应用矩阵变换
  //     // canvas.transform(rotationMatrix.storage);
  //   }
  //
  //   canvas.drawImageRect(
  //     img,
  //     Rect.fromLTRB(0, 0, img.width.toDouble(), img.height.toDouble()),
  //     // 如果要居中，就调这里的 x，y值
  //     Rect.fromLTRB(0, 0, renderWidth, renderHeight),
  //     Paint(),
  //   );
  //
  //   final imgRect = Offset.zero & imgSize;
  //   rectElements.add(
  //       RectInfoModel(rect: scaleRect ?? imgRect, type: CanvasEventType.image));
  //
  //   // if (scaleRect != null) {
  //   //   //重置缩放
  //   //   canvas.restore();
  //   // }
  //   // if (true) {
  //   //   //重置缩放
  //   //   canvas.restore();
  //   // }
  //   canvas.restoreToCount(count);
  //   canvas.drawRect(
  //       scaleRect ?? imgRect,
  //       paint
  //         ..style = ui.PaintingStyle.stroke
  //         ..color = showAction == true
  //             ? Colors.deepOrangeAccent
  //             : Colors.transparent);
  //   if (showAction) {
  //     List<RectInfoModel> rectList = drawSvgIcon(canvas, paint,
  //         iconOffset: svgIconOffset,
  //         iconSize: svgIconSize,
  //         boxSize: scaleRect == null
  //             ? imgSize
  //             : ui.Size(scaleRect!.width, scaleRect!.height),
  //         svgList: svgList);
  //     rectElements.addAll(rectList);
  //   }
  //   canvas.restore();
  // }

  @override
  bool shouldRepaint(covariant MyCustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return svgList != oldDelegate.svgList ||
        showAction != oldDelegate.showAction ||
        dx != oldDelegate.dx ||
        dy != oldDelegate.dy ||
        imgSize != imgSize ||
        scaleRect != oldDelegate.scaleRect;
  }
}

List<RectInfoModel> drawSvgIcon(
  Canvas canvas,
  Paint paint, {
  List<svg.PictureInfo> svgList = const [],
  double iconOffset = 5,
  double padding = 10,
  ui.Size iconSize = const ui.Size(30, 30),
  ui.Size boxSize = const ui.Size(100, 100),
}) {
  List<RectInfoModel> _rectList = [];
  if (svgList.isNotEmpty) {
    for (int i = 0; i < svgList.length; i++) {
      if (i == 0) {
        // 删除
        drawRectSingleSvg(
          canvas,
          paint,
          svgList[i],
          rectElements: _rectList,
          eventType: CanvasEventType.delete,
          boxSize: boxSize,
          iconSize: iconSize,
          padding: padding,
          iconOffset: iconOffset,
        );
      } else if (i == 1) {
        // 锁头
        // icon为size = 30的圆，内边距为5的icon

        drawRectSingleSvg(
          canvas,
          paint,
          svgList[i],
          rectElements: _rectList,
          eventType: CanvasEventType.lock,
          boxSize: boxSize,
          iconSize: iconSize,
          padding: padding,
          iconOffset: iconOffset,
        );
      } else if (i == 2) {
        // 翻转
        drawRectSingleSvg(
          canvas,
          paint,
          svgList[i],
          rectElements: _rectList,
          eventType: CanvasEventType.rotate,
          boxSize: boxSize,
          iconSize: iconSize,
          padding: padding,
          iconOffset: iconOffset,
        );
      } else {
        // 缩放
        drawRectSingleSvg(
          canvas,
          paint,
          svgList[i],
          rectElements: _rectList,
          eventType: CanvasEventType.scale,
          boxSize: boxSize,
          iconSize: iconSize,
          padding: padding,
          iconOffset: iconOffset,
        );
      }
    }
  }
  return _rectList;
}

drawRectSingleSvg(
  ui.Canvas canvas,
  Paint paint,
  svg.PictureInfo svgInfo, {
  double padding = 30,
  List<RectInfoModel> rectElements = const [],
  ui.Size boxSize = const ui.Size(100, 100),
  ui.Size iconSize = const ui.Size(30.0, 30.0),
  double iconOffset = 0,
  CanvasEventType eventType = CanvasEventType.image,
}) {
  var count = canvas.getSaveCount();
  canvas.save();

  Rect iconBoxRect;
  if (eventType == CanvasEventType.delete) {
    // 左上
    iconBoxRect = Offset(-(iconSize.width.toDouble() - iconOffset),
            -(iconSize.height.toDouble() - iconOffset)) &
        iconSize;
  } else if (eventType == CanvasEventType.lock) {
    // 右上
    iconBoxRect = Offset(boxSize.width - iconOffset,
            -(iconSize.height.toDouble() - iconOffset)) &
        iconSize;
  } else if (eventType == CanvasEventType.rotate) {
    // 左下
    iconBoxRect = Offset(-(iconSize.width.toDouble() - iconOffset),
            boxSize.height - iconOffset) &
        iconSize;
  } else {
    // 缩放 右下
    iconBoxRect =
        Offset(boxSize.width - iconOffset, boxSize.height - iconOffset) &
            iconSize;
  }
  // = ui.Offset.zero &
  //     Size(resizeWidth.toDouble() + iconDx, resizeHeight.toDouble() + iconDy);
  rectElements.add(RectInfoModel(rect: iconBoxRect, type: eventType));
  canvas.drawOval(
      iconBoxRect,
      paint
        ..color = Colors.black45
        ..style = ui.PaintingStyle.fill);

  if (eventType == CanvasEventType.delete) {
    canvas.translate(-(iconSize.width - (padding + iconOffset * 2) / 2),
        -(iconSize.height - (padding + iconOffset * 2) / 2));
  } else if (eventType == CanvasEventType.lock) {
    canvas.translate((boxSize.width + (padding - iconOffset * 2) / 2),
        -(iconSize.height - (padding + iconOffset * 2) / 2));
  } else if (eventType == CanvasEventType.rotate) {
    canvas.translate(-(iconSize.width - (padding + iconOffset * 2) / 2),
        boxSize.height + (padding - iconOffset * 2) / 2);
  } else {
    canvas.translate(boxSize.width + (padding - iconOffset * 2) / 2,
        boxSize.height + (padding - iconOffset * 2) / 2);
  }
  // 新建一个图层，然后使用colorFilter的着色器给画板上色，就可以绘制picture的颜色了

  drawResizeSvg(
      canvas,
      svgInfo.picture,
      ui.Size(iconSize.width - padding, iconSize.height - padding),
      svgInfo.size);
  canvas.restoreToCount(count);
}

void drawResizeSvg(
    ui.Canvas canvas, ui.Picture picture, ui.Size iconSize, ui.Size originSize,
    {ui.Color? color = Colors.white}) {
  ui.Paint _paint = ui.Paint();
  if (color != null) {
    _paint..colorFilter = ColorFilter.mode(color, BlendMode.srcIn);
  }
  canvas.saveLayer(
    null,
    _paint,
  );
  // canvas.translate(-size.width / 2, 0);
  canvas.scale(
      iconSize.width / originSize.width, iconSize.height / originSize.height);

  // 先定位好点，然后绘制
  canvas.drawPicture(picture);
  canvas.restore();
}
